<?php
declare (strict_types=1);

namespace magein\sms\service\think;

use magein\sms\Send;
use magein\sms\SmsException;
use magein\utils\Result;
use think\App;
use think\Exception;
use think\facade\Queue;
use think\facade\Request;
use think\response\Json;

class SmsController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * @var Send
     */
    protected $send = null;

    public function __construct(App $app)
    {
        $this->app = $app;
        $this->request = $this->app->request;
        $this->send = $this->app->sms->send;
    }

    /**
     * @return Json
     */
    public function code()
    {
        $data = $this->request->post();

        try {
            $result = $this->send->code($data);
        } catch (SmsException $smsException) {
            $result = $smsException->toResult();
        }

        return json($result->toArray());
    }

    /**
     * @return Json
     */
    public function message(): Json
    {
        $data = $this->request->post();

        try {
            $result = $this->send->message($data);
        } catch (SmsException $smsException) {
            $result = $smsException->toResult();
        }

        return json($result->toArray());
    }

    /**
     * @return Json
     */
    public function batch(): Json
    {
        $data = $this->request->post();

        try {
            $platform = $this->send->platform($data);
        } catch (SmsException $exception) {
            return json($exception->toArray());
        }

        try {
            $result = Queue::push(SmsJob::class, $data, SmsJob::NAME);
        } catch (Exception $exception) {
            $result = null;
        }

        if ($result) {
            return json(Result::success($result, '添加到队列成功')->toArray());
        }

        return json(Result::error('添加到队列失败')->toArray());
    }

    /**
     * @return Json
     */
    public function delay(): Json
    {
        $data = $this->request->post();

        try {
            $platform = $this->send->platform($data);
        } catch (SmsException $exception) {
            return json($exception->toArray());
        }

        $delay = intval($data['delay'] ?? 0);
        if ($delay <= 0) {
            $delay = rand(0, 10);
        }
        $data['delay'] = $delay;

        try {
            $result = Queue::later($delay, SmsJob::class, $data, SmsJob::NAME);
        } catch (Exception $exception) {

        }

        if ($result) {
            return json(Result::success($result, '添加到队列成功')->toArray());
        }

        return json(Result::error('添加到队列失败')->toArray());
    }
}